/*
 * @Author: jiu yin
 * @Date: 2023-12-08 17:00:57
 * @LastEditTime: 2024-08-19 16:22:15
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\comment\FormTwo\index.tsx
 * jiu
 */
import { useEffect, useState, forwardRef, useImperativeHandle } from "react";
import {
   AutoComplete,
   Button,
   Cascader,
   Checkbox,
   Radio,
   Switch,
   Col,
   Form,
   Input,
   InputNumber,
   Row,
   Select,
   DatePicker,
   Image
} from "antd";

import dayjs from "dayjs";

import Upload_card from "@/comment/upload";

import { EyeInvisibleOutlined, EyeTwoTone } from "@ant-design/icons";

const FormTwo = forwardRef((props: any, ref) => {
   /*
      layout:表单布局 horizontal | vertical | inline
      formList:表单列表  每一项不一样的属性 具体看 antd
      举例：{
         type:"text",
         label:"文本",
         validateStatus:"warning",//校验状态  'success', 'warning', 'error', 'validating'。
         children:(<span className="red">尼玛</span>)
      }
       */
   const {
      formItemLayout = {
         labelCol: {
            span: 4
         }
      },
      layout = "vertical", //horizontal | vertical | inline
      style = { maxWidth: 400, grid_cols: 4 },
      name = new Date().getTime(),
      size = "default", //small default large
      submitText = "确定",
      isButton = true,
      className = "",
      btnOffset = 8
   } = props.formTwoProps || {};

   let [formList = [], setFormList] = props.formList; //json表单列表
   //隐藏hidden
   let formList_filter = formList.filter((item: any) => item.hidden != true);

   let [formData, setFormData, dataFormRoleInfo] = props.formData; //数据

   const [form] = Form.useForm();

   //成功
   const onFinish = (values: any) => {
      //处理时间
      let result = datePicker_data(values);

      //处理undefined 的值
      let obj = {} as any;
      for (let key in result) {
         if (result[key] !== undefined) obj[key] = result[key];
      }
      props.onFinish(obj);
   };

   //取消
   const cancel = () => {
      setFormData({ ...dataFormRoleInfo });
      props.cancel();
   };

   //重置表单
   useEffect(() => {
      form.setFieldsValue(formData);
   }, [formData]);

   //处理表单的时间  返回字符串
   const datePicker_data = (values: any) => {
      formList_filter.forEach((item: any) => {
         //单个时间
         if (item.type == "datePicker") {
            values[item.name] = values[item?.name] && antDate(values[item.name]);
         }
         //时间范围
         if (item.type == "rangePicker") {
            values[item.name] = values[item?.name] && [antDate(values[item.name][0]), antDate(values[item.name][1])];
         }
      });
      return values;
   };

   //处理ant 时间格式
   const antDate = (date: any) => {
      if (date) {
         return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
      } else {
         return "";
      }
   };

   //暴露给父组件的方法
   useImperativeHandle(
      ref,
      () => {
         return {
            cancel,
            form
         };
      },
      []
   );

   //info 数据
   useEffect(() => {
      formList.forEach((item: any) => {
         //处理异步请求 所有异步的options都会在这里处理
         if (item.optionsAsync) {
            item.optionsAsync(item.params || null).then((res: any) => {
               console.log("res", res);
               if (item.request_data) {
                  let arr = item.request_data.split(".");
                  item.options = obj_recursion(res, arr);
               } else {
                  item.options = res;
               }
               setFormList([...formList]);
            });
         }
      });
   }, []);

   //循环返回深层对象
   function obj_recursion(obj: any, arr_key: any[] = []) {
      if (arr_key.length == 0) return obj;
      let obj_temp = { ...obj };
      arr_key.forEach((item: any) => {
         obj_temp = obj_return(obj_temp, item);
      });
      return obj_temp;
   }
   //返回对象属性
   function obj_return(obj: any, key: string) {
      return obj[key];
   }

   //表单列表处理
   const formList_dispose = (arr: any) => {
      return arr.map((item: any, index: number) => {
         switch (item.type) {
            case "div":
               return (
                  <Form.Item label={item.label} key={index} {...item.attr}>
                     {item.children}
                  </Form.Item>
               );
            //嵌套item 配合div使用
            case "nest_item":
               return (
                  <Form.Item label={item.label} key={index} required={item.required}>
                     <div className={item.wrapClassName}>{item.children && formList_dispose(item.children)}</div>
                  </Form.Item>
               );

            case "input":
               return (
                  <Form.Item
                     label={item.label}
                     name={item.name}
                     validateStatus={item.validateStatus}
                     rules={item.rules || null}
                     required={item.required}
                     validateTrigger={item.validateTrigger || "onChange"}
                     key={index}
                  >
                     <Input
                        style={item.style}
                        autoComplete={item.autoComplete || "on"}
                        maxLength={item.maxLength}
                        minLength={item.minLength}
                        disabled={item.disabled}
                        prefix={item.prefix || ""}
                        suffix={item.suffix || ""}
                        onChange={item.onChange}
                        onFocus={item.onFocus}
                        onBlur={item.onBlur}
                        value={item.value}
                        placeholder={item.placeholder || ""}
                        onClick={item.onClick}
                     />
                  </Form.Item>
               );
            case "inputPassword":
               return (
                  <Form.Item
                     label={item.label}
                     name={item.name}
                     validateStatus={item.validateStatus}
                     rules={item.rules || null}
                     required={item.required}
                     key={index}
                  >
                     <Input.Password
                        autoComplete={item.autoComplete || "on"}
                        style={item.style}
                        disabled={item.disabled}
                        prefix={item.prefix || ""}
                        suffix={item.suffix || ""}
                        onChange={item.onChange}
                        placeholder={item.placeholder || ""}
                        iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                     />
                  </Form.Item>
               );
            case "inputNumber":
               return (
                  <Form.Item
                     label={item.label}
                     name={item.name}
                     validateStatus={item.validateStatus}
                     rules={item.rules || null}
                     required={item.required}
                     key={index}
                  >
                     <InputNumber
                        style={item.style}
                        //error warning success
                        status={item.status}
                        disabled={item.disabled}
                        onChange={item.onChange}
                        //精度 0  整数  1 一位小数  2 两位小数
                        precision={item.precision}
                        min={item.min}
                        max={item.max}
                        maxLength={item.maxLength}
                        controls={item.controls}
                        //前缀
                        prefix={item.prefix || ""}
                        //前后组件
                        addonBefore={item.addonBefore || ""}
                        addonAfter={item.addonAfter || ""}
                        placeholder={item.placeholder || ""}
                        defaultValue={item.defaultValue}
                     />
                  </Form.Item>
               );
            case "select":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     <Select
                        disabled={item.disabled}
                        showSearch={item.showSearch} //'true' | 'false'
                        placeholder={item.placeholder}
                        defaultValue={item.defaultValue}
                        style={item.style}
                        mode={item.mode} //multiple 多选 | tags 标签
                        //远程搜索就要设置为false 不然要冲突
                        filterOption={item.filterOption || item?.optionsAsync ? false : true}
                        optionFilterProp="label"
                        onChange={item.onChange}
                        onSearch={item.onSearch}
                        options={item.options}
                     ></Select>
                  </Form.Item>
               );
            case "textArea":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     <Input.TextArea
                        showCount
                        style={item.style}
                        disabled={item.disabled}
                        maxLength={item.maxLength || 100}
                        rows={item.rows || 6}
                        placeholder={item.placeholder || ""}
                     />
                  </Form.Item>
               );
            case "checkbox":
               return (
                  <Form.Item
                     label={item.label}
                     name={item.name}
                     valuePropName="checked"
                     key={index}
                     rules={item.rules || null}
                     required={item.required}
                  >
                     <Checkbox disabled={item.disabled} style={item.style} onChange={item.onChange}>
                        {item.checkboxText}
                     </Checkbox>
                  </Form.Item>
               );
            case "checkboxGroup":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     <Checkbox.Group
                        disabled={item.disabled}
                        style={item.style}
                        onChange={item.onChange}
                        options={item.options}
                        value={formData[item.name]}
                     />
                  </Form.Item>
               );
            case "radio":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     <Radio.Group
                        disabled={item.disabled}
                        onChange={item.onChange}
                        options={item.options}
                        value={formData[item.name]}
                     />
                  </Form.Item>
               );
            case "switch":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} required={item.required}>
                     <Switch
                        disabled={item.disabled}
                        checkedChildren={item.checkedChildren}
                        unCheckedChildren={item.unCheckedChildren}
                        onChange={item.onChange}
                        // checked={formData[item.name]}
                        defaultChecked={formData[item.name]}
                     />
                  </Form.Item>
               );
            case "image":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} required={item.required}>
                     <Image width={item.width || 200} height={item.height || 200} src={item.src} />
                  </Form.Item>
               );
            //单个时间
            case "datePicker":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     {/* picker：week| month|year|date|quarter  */}
                     <DatePicker
                        disabled={item.disabled}
                        showTime={item.showTime}
                        style={item.style}
                        format={item.format || "YYYY-MM-DD HH:mm"}
                        onChange={item.onChange}
                        picker={item.picker}
                     />
                  </Form.Item>
               );
            //组合时间
            case "rangePicker":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     {/*
                      picker：week| month|year|date|quarter
                      showTime={{
                       hideDisabledOptions: true,
                       defaultValue: [dayjs('00:00:00', 'HH:mm:ss'), dayjs('11:59:59', 'HH:mm:ss')],
                       }}
                     */}
                     <DatePicker.RangePicker
                        disabled={item.disabled}
                        style={item.style}
                        onChange={item.onChange}
                        picker={item.picker}
                        disabledDate={item.disabledDate}
                        format={item.format || "YYYY-MM-DD HH:mm"}
                        showTime={item.showTime}
                     />
                  </Form.Item>
               );
            //
            case "upload_card":
               return (
                  <Form.Item
                     label={item.label}
                     name={item.name}
                     key={index}
                     rules={item.rules || null}
                     style={item.style}
                     required={item.required}
                  >
                     <Upload_card
                        disabled={item.disabled}
                        listType={item.listType}
                        action_url={item.action_url}
                        count={item.count}
                        data={item.data}
                        fileSize={item.fileSize}
                        beforeUpload_fn={item.beforeUpload_fn}
                        onRemove={item.onRemove}
                        accept={item.accept}
                        className={item.className}
                        fileList={item.fileList}
                        uploadButton={item.uploadButton}
                     />
                  </Form.Item>
               );

            case "button":
               return <Form.Item key={index}>{item.children}</Form.Item>;
            case "cascader":
               return (
                  <Form.Item label={item.label} name={item.name} key={index} rules={item.rules || null} required={item.required}>
                     <Cascader
                        disabled={item.disabled}
                        options={item.options}
                        placeholder={item.placeholder || "请选择"}
                        onChange={item.onChange}
                        onClick={item.onClick}
                     />
                  </Form.Item>
               );
            default:
               break;
         }
      });
   };

   return (
      <div ref={ref as React.RefObject<HTMLDivElement>} className={className}>
         <Form
            {...formItemLayout}
            layout={layout}
            form={form}
            name={name}
            onFinish={onFinish}
            initialValues={formData}
            style={{ ...style }}
            size={size}
            scrollToFirstError
         >
            {layout == "inline" ? (
               <div className="w-100% grid grid-cols-4 grid-gap-16px">
                  {/* 表单列表 */}
                  {formList_dispose(formList_filter)}
               </div>
            ) : (
               <>{formList_dispose(formList_filter)}</>
            )}

            {isButton && (
               <Form.Item wrapperCol={{ offset: btnOffset, span: 16 }}>
                  <Button type="primary" htmlType="submit">
                     {submitText}
                  </Button>
                  <Button
                     htmlType="button"
                     onClick={() => {
                        cancel();
                     }}
                     className="ml_10"
                  >
                     取消
                  </Button>
               </Form.Item>
            )}
         </Form>
      </div>
   );
});
export default FormTwo;
